package com.my.easymall.listener;

import com.my.easymall.domain.User;
import org.apache.log4j.Logger;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

/**
 * @auther Summerday
 */

@WebListener()
public class UserRequestListener implements ServletRequestListener {
    private static Logger logger = Logger.getLogger(UserRequestListener.class);
    //用户请求结束
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {

        //判断当前请求中是否包含用户的登录信息
        //获取用户名 ip  请求的url
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        String username = "游客";
        if (request.getSession(false) != null && request.getSession().getAttribute("user") != null) {
            User user = (User) request.getSession().getAttribute("user");
            username = user.getUsername();
        }
        String url = request.getRequestURL().toString();

        String ip = request.getRemoteAddr();
        logger.debug("用户:" + username + "||ip:" + ip + "||url:" + url+"访问结束");

    }

    //用户请求开始
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        //判断当前请求中是否包含用户的登录信息
        //获取用户名 ip  请求的url
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        String username = "游客";
        if (request.getSession(false) != null && request.getSession().getAttribute("user") != null) {
            User user = (User) request.getSession().getAttribute("user");
            username = user.getUsername();
        }
        String url = request.getRequestURL().toString();

        String ip = request.getRemoteAddr();
        logger.debug("用户:" + username + "||ip:" + ip + "||url:" + url+"访问开始");
    }
}
